'''
    什么是中间件？
    中间件就是一个函数，这个函数可以处理请求，也可以处理响应，可以处理异常，可以处理其他任何事情。
    在开发中，我们经常会用到中间件，比如：
    1. 日志记录
    2. 权限验证
    3. 异常处理
    4. 缓存
    这里使用中间件是因为，我们需要在请求和响应之间做一些事情，比如：
    1，将数据库中的数据绑定到列表中
    2，统一配置数据库服务，使得程序更加健壮
    3，简化一些功能的步骤
'''
import time
from config.Instrument import Instrument_toml
from models.user_model import UserModel
from dao.Result import Result 
from models.leave_model import LeaveModel
from dao.Result_his import Result as re_s
from dao.Result_feature import Result as Res
import json
from dao.Result_leave_history import Result as Res_h

class Middleware:
    def __init__(self):
        pass
    def data_binding_user(self):
        temp = Result(**self.get_config())
        temp.start()
        data = temp.query("user")
        ans = []
        for  i in data:
            user_model = UserModel()
            try:
                user_model.setuser(i[0], i[3], i[2], i[1], i[4])
            except:
                user_model.setuser(i[0], i[3], i[2], i[1], "")
            ans_t = user_model.getuser()
            ans.append(ans_t)

        return ans
    
    def contian(self,nickname):
        temp = Result(**self.get_config())
        temp.start()
        data = temp.query_by_id(nickname)
        return data != None
    
    def data_binding_user_by_id(self,nickname):
        temp = Result(**self.get_config())
        temp.start()
        data = temp.query_by_id(nickname)
        user_model = UserModel()
        user_model.setuser(data[0], data[3], data[2], data[1], data[4])
        ans = user_model.getuser()
        return ans
    
    def get_config(self):
        toml = Instrument_toml()
        user = toml.GetStrogeToml("user")
        password = toml.GetStrogeToml("password")
        database = toml.GetStrogeToml("database")
        url = toml.GetStrogeToml("url")

        return {
            "url": url,
            "user": user,
            "password": password,
            "db": database
        }
    
    def data_binding_his(self):
        dic = self.get_config()
        temp = re_s(**dic)
        temp.start()
        data = temp.query()
        ans = []
        for i in data:
            leave_model = LeaveModel()
            try:
                leave_model.setleave(i[0], i[1], i[2], i[3], i[4], i[5], i[6])
            except:
                leave_model.setleave(i[0], i[1], i[2], i[3], i[4], i[5], "")
            ans_t = leave_model.getleave()
            ans.append(ans_t)
        temp.close()
        return ans
    
    #懒得去数据库，手写一个多表联查
    #等价于select * from user left join leval on user.user_id = leave.leave_user
    def data_binding_user_leave(self):
        ans1 = self.data_binding_user()
        ans2 = self.data_binding_his()
        for i in ans2:
            temp = i['reviewedBy']
            for j in ans1:
                users = j['user_id']
                if temp == users:
                    i['username'] = j['nickname']
                    continue
        ans2.reverse()
        return ans2

    #再来个多表联查吧
    def data_bind_his(self):
        res = Res_h(**self.get_config())
        res.start()
        ans = res.query()
        res.close()
        res1 = Result(**self.get_config())
        res1.start()
        dic={'时间':[],'教师':[],'班级':[],'缺勤名单':[]}
        for i in ans:
            tim = i[1]
            class_ = i[2]
            no = i[-1]
            id = res1.query_by_user_id(i[-2])[3]
            dic['教师'].append(id)
            dic["时间"].append(tim)
            dic['班级'].append(class_)
            dic['缺勤名单'].append(json.loads(no))
        res1.close()
        return dic
    
    def calculate(self,**data):
        #从班级列表里面获取所有人
        temp = Res(**self.get_config())
        temp.start()
        user = temp.query()
        temp.close()
        user_c = []

        for i in user:
            # chinese_text = i.decode('utf-8')
            if i[-2] == data["class"]:
                user_c.append([i[1],i[-1]])

        #对比列表中的人
        time_str = time.strftime("%Y-%m-%d", time.localtime())
        res1 = Res_h(**self.get_config())
        res1.start()
        if len(data['lis']) == len(user_c):
            dic = {
                "time" : time_str,
                "class_info" : data['class'],
                "user_name" : data['user_id'],
                "leave"     : json.dumps([])
            }
            res1.insert(**dic)
            res1.close()
            return []
        else:
            ans = self.find_difference(data['lis'],user_c)
            dic = {
                "time" : time_str,
                "class_info" : data['class'],
                "user_name" : data['user_id'],
                "leave"     : json.dumps(ans,ensure_ascii=False)
            }
            res1.insert(**dic)
            res1.close()
            return ans

        
    def find_difference(self,list1, list2):
        result = []
        ans = []
        for  i in list1:
            if i in [j[0] for j in list2]:
                result.append(i)
        if len(result) != 0:
            for i in list2:
                if i[0] not in result:
                    ans.append(i[1])
        else:
            ans = [i[1] for i in list2]
        return ans

        
    
    def get_new_his(self):
        res = Res_h(**self.get_config())
        res.start()
        ans =  res.query()[-1]
        res.close()
        class_ = ans[2]
        leave = json.loads(ans[-1])
        re = Res(**self.get_config())
        re.start()
        count = len(re.query_by_class_name(class_))
        dic = {
            "all" : count,
            "leave" : len(leave),
            "t" : count - len(leave)
        }
        return [dic,leave]